<template>
  <div class="app-container">
    <!-- 查询 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="姓名" prop="studentName">
        <el-input v-model="queryParams.studentName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" clearable placeholder="性别">
          <el-option v-for="d in sys_user_sex" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="状态">
          <el-option v-for="d in sys_normal_disable" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          unlink-panels
          :shortcuts="dateShortcuts"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:student:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:student:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:student:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:student:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="90" />
      <el-table-column label="姓名" prop="studentName" min-width="120" />
      <el-table-column label="性别" prop="gender" width="100">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" width="90" />
      <el-table-column label="班级" prop="className" min-width="140" />
      <el-table-column label="手机" prop="phone" min-width="140" />
      <el-table-column label="状态" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" min-width="170" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:student:edit']">修改</el-button>
          <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:student:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗 -->
    <el-dialog :title="title" v-model="open" width="520px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option v-for="d in sys_user_sex" :key="d.value" :label="d.label" :value="d.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="150" style="width: 100%" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '../../../utils/dict'
import { listStudent, getStudent, addStudent, updateStudent, delStudent, exportStudent } from '../../../api/system/student'

const { proxy } = getCurrentInstance() as any
const { sys_user_sex, sys_normal_disable } = useDict('sys_user_sex', 'sys_normal_disable')

const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const list = ref<any[]>([])
const single = ref(true)
const multiple = ref(true)
const open = ref(false)
const title = ref('')

const queryRef = ref()
const formRef = ref()

const dateRange = ref<[string, string] | []>([])
const dateShortcuts = [
  { text: '近7天', value: () => { const e = new Date(); const s = new Date(); s.setDate(e.getDate() - 6); return [s, e] } },
  { text: '近30天', value: () => { const e = new Date(); const s = new Date(); s.setDate(e.getDate() - 29); return [s, e] } }
]

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  studentName: undefined,
  phone: undefined,
  gender: undefined,
  status: undefined
})

const form = reactive<any>({
  id: undefined,
  studentName: undefined,
  gender: '0',
  age: undefined,
  className: undefined,
  phone: undefined,
  status: '0',
  remark: undefined
})

const rules = reactive<any>({
  studentName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

function buildQuery() {
  // 兼容后端 BaseEntity 的 params.beginTime / endTime
  const q: any = { ...queryParams }
  if (dateRange.value && dateRange.value.length === 2) {
    q.params = {
      beginTime: dateRange.value[0] + ' 00:00:00',
      endTime: dateRange.value[1] + ' 23:59:59'
    }
  }
  return q
}
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    studentName: undefined,
    phone: undefined,
    gender: undefined,
    status: undefined
  })
  dateRange.value = []
  getList()
}

function handleSelectionChange(selection: any[]) {
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
  selectedIds.value = selection.map((r) => r.id)
}

const selectedIds = ref<number[]>([])

function resetForm() {
  Object.assign(form, {
    id: undefined,
    studentName: undefined,
    gender: '0',
    age: undefined,
    className: undefined,
    phone: undefined,
    status: '0',
    remark: undefined
  })
  formRef.value?.clearValidate?.()
}

function handleAdd() {
  resetForm()
  title.value = '新增学生'
  open.value = true
}

function handleUpdate(row?: any) {
  const id = row?.id ?? selectedIds.value[0]
  if (!id) return
  getStudent(id).then((res: any) => {
    Object.assign(form, res.data || {})
    title.value = '修改学生'
    open.value = true
  })
}

function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return
    const req = form.id ? updateStudent : addStudent
    req(form).then(() => {
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      open.value = false
      getList()
    })
  })
}

function handleDelete(row?: any) {
  const ids = row?.id ? [row.id] : selectedIds.value
  if (!ids.length) return
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条记录吗？`, '提示', { type: 'warning' })
    .then(() => delStudent(ids.join(',')))
    .then(() => {
      ElMessage.success('删除成功')
      getList()
    })
}

// ...existing code...
function handleExport() {
  // 若工程内已注入 download 助手，优先使用（自动处理 token 与文件名）
  if (proxy?.download) {
    proxy.download('/system/student/export', buildQuery(), `学生数据_${Date.now()}.xlsx`)
    return
  }

  exportStudent(buildQuery()).then((res: any) => {
    const blob = res instanceof Blob ? res : res.data || res
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `学生数据_${Date.now()}.xlsx`
    document.body.appendChild(link) // 更兼容的做法
    link.click()
    link.remove()
    window.URL.revokeObjectURL(url)
  })
} // <- 添加缺失的闭合大括号，修复语法错误

function cancel() {
  open.value = false
}

function getList() {
  loading.value = true
  listStudent(buildQuery())
    .then((res: any) => {
      const data = res && res.data ? res.data : res
      const rows = data?.rows ?? data?.list ?? (Array.isArray(data) ? data : [])
      list.value = Array.isArray(rows) ? rows : []
      total.value = Number(data?.total ?? data?.totalCount ?? list.value.length) || 0

      // 重置选择状态（避免上一页选择影响当前页）
      selectedIds.value = []
      single.value = true
      multiple.value = true
    })
    .catch((err: any) => {
      console.error('获取列表失败：', err)
      ElMessage.error('获取列表失败，请稍后重试')
    })
    .finally(() => {
      loading.value = false
    })
}
// ...existing code...
</script>